package org.wanho.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * Author：汤小洋
 * Date：2023-04-24 9:36
 * Description：<描述>
 */
@WebServlet("/cookie")
public class CookieServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Cookie cookie = new Cookie("name", URLEncoder.encode("周易","utf-8")); // 存储中文时需要对中文进行编码
        // Cookie cookie2 = new Cookie("age", "18");
        //
        // cookie2.setMaxAge(7*24*60*60); // 7天
        // cookie2.setPath("/"); // 设置为/，可以实现同一服务内的不同应用之间的共享
        // cookie2.setMaxAge(0); // 清除

        // resp.addCookie(cookie);
        // resp.addCookie(cookie2);

        /**
         * 读取Cookie
         */
        Cookie[] cookies = req.getCookies();
        for (Cookie c : cookies){
            System.out.println(c.getName()+"------------"+ URLDecoder.decode(c.getValue(),"utf-8"));
        }

        /**
         * 使用CookieUtil
         */
        // CookieUtil.addCookie("sex","男", 24*60*60, resp);
        //
        // System.out.println(CookieUtil.findByName("age",req));


    }
}
